import requests
import json
import time

api_key = "app-r7gcgA6KDtDNPGLVXJMm1SD4"

conversation_ids={}
def send_chat_message_dify(query, user=""):
    url = "http://49.235.97.4:8115/v1/chat-messages"
    headers = {
        "Authorization": f"Bearer {api_key}",
        "Content-Type": "application/json"
    }

    if query == "重新出方案":
        if user in conversation_ids:
            del conversation_ids[user]
    conversation_id = conversation_ids.get(user, None)

    data = {
        "inputs": {},
        "query": query,
        "response_mode": "blocking",
        "conversation_id": conversation_id,
        "user": user
    }
    response = requests.post(url, headers=headers, data=json.dumps(data))
    response_json= response.json()
    if response.status_code == 200:
        conversation_id = response_json["conversation_id"]
        conversation_ids[user] = conversation_id
        return response_json["answer"]
    else:
        return "Error: " + response.text

def send_chat_message_coze(query):
    print("llm_response, 开始使用大模型生成答复...")
    start_time = time.perf_counter()
# ==================== API 配置 ====================
    api_url = "https://api.coze.cn/open_api/v2/chat"  # V2 接口地址
    coze_token = "##################"
    bot_id = "7487567758625292314"
    headers = {
        'Authorization': f'Bearer {coze_token}',
        'Content-Type': 'application/json',
        'Accept': 'text/event-stream'
    }
    payload = {
        "bot_id": bot_id,
        "user": "user_123",  # V2 使用 user 字段
        "query": query,
        "stream": True
    }
    # ==================== 请求处理 ====================

    my_answer = ""
    buffer = ""  # 数据缓冲区
    first_chunk = True

    try:
        response = requests.post(
            api_url,
            headers=headers,
            json=payload,
            stream=True,
            timeout=30
        )
        response.raise_for_status()

        # 处理流式响应
        for chunk in response.iter_content(chunk_size=1024):
            if chunk:
                chunk_str = chunk.decode('utf-8')
                print(f"接收到数据chunk_str: {chunk_str}")
                buffer += chunk_str

                # 分割完整事件块（V2 使用 \n\n 分隔）
                while "\n\n" in buffer:
                    event_str, buffer = buffer.split("\n\n", 1)

                    # 跳过非数据行（如心跳包）
                    if not event_str.startswith("data:"):
                        continue

                    # 记录首块时间
                    if first_chunk:
                        print(f"首块到达时间: {time.perf_counter() - start_time:.2f}s")
                        first_chunk = False

                    # 解析 JSON
                    try:
                        json_str = event_str[len("data:"):].strip()
                        event_data = json.loads(json_str)

                        # 处理消息事件
                        if event_data.get("event") == "message":
                            msg = event_data.get("message", {})
                            if msg.get("type") == "answer":
                                content = msg.get("content", "")

                                # 处理分块文本
                                result = ""
                                last_pos = 0
                                for i, char in enumerate(content):
                                    if char in ",.!;:，。！？：；":
                                        result += content[last_pos:i + 1]
                                        last_pos = i + 1

                                        # 当积累足够内容时推送
                                        if len(result) > 10:
                                            print(f"推送分块: {result}")
                                            my_answer += result
                                            result = ""

                                # 处理剩余内容
                                result += content[last_pos:]
                                if result:
                                    print(f"result: {result}")
                                    my_answer += result

                        # 处理错误事件
                        elif event_data.get("event") == "error":
                            error_info = event_data.get("error_information", {})
                            print(f"API错误 [{error_info.get('code')}]: {error_info.get('msg')}")
                            print(f"my_answer: {my_answer}")
                            return f"API错误 [{error_info.get('code')}]: {error_info.get('msg')}"

                    except json.JSONDecodeError as e:
                        print(f"JSON解析失败: {e} | 原始数据: {event_str}")
                        continue

    except requests.exceptions.RequestException as e:
        print(f"请求失败: {str(e)}")
        print(f"my_answer: {my_answer}")
        return f"请求失败: {str(e)}"
    except Exception as ex2:
        print("其它发生异常", ex2)
        print(f"my_answer: {my_answer}")
        return f"其它发生异常: {str(ex2)}"


    # ==================== 最终处理 ====================
    print(f"总处理时间: {time.perf_counter() - start_time:.2f}s")

    return my_answer

if __name__ == "__main__":
    response= send_chat_message_coze("你好")
    print(response)
